#!/usr/bin/perl

# $Id: storage_test.pl 34 2010-11-12 11:52:29Z dolbanavt@googlemail.com $
# $Date: 2010-11-12 13:52:43 +0200 (Птн, 12 Ноя 2010) $
# $HeadURL: https://tegusigalpa.googlecode.com/svn/branches/storage_init/storage_test.pl $
# $LastChangedRevision$

use lib::abs qw( base_lib );
use JIP::ToolSet;
use Carp qw( carp );
use Const::Fast qw( const );
use Pod::Usage qw( pod2usage );
use Getopt::Long 2.24 qw( :config no_auto_abbrev no_ignore_case );
use File::Spec::Functions qw( catfile );
use FindBin qw( $RealBin );
use Configurator;
use Log::Console;
use JSON::RPC::Client;
use Object::Container 'container';

our $VERSION = '1.0';

# more meaningfull names for pod2usage's -verbose parameter
const my $SHOW_USAGE_ONLY         => 0;
const my $SHOW_BRIEF_HELP_MESSAGE => 1;
const my $SHOW_FULL_MANUAL        => 2;

# more meaningfull names for pod2usage's -exitval parameter
const my $RETURN_SUCCESS     => 0;
const my $RETURN_FATAL_ERROR => 1;
const my $RETURN_BAD_OPTIONS => 2;

# дефолтный локейшен RPC-сервера
const my $REMOTE_SERVER_URL => 'http://localhost';

#-- ui -------------------------------------------------------------------------
my $options_okay = GetOptions(
    'help'   => \my $is_help_requested,
    'conf=s' => \my $path_to_conf_file,
    'url=s'  => \my $remote_server_url,
);

# show appropriate help message
pod2usage( -exitval => $RETURN_BAD_OPTIONS, -verbose => $SHOW_USAGE_ONLY )
    unless $options_okay;

pod2usage( -exitval => $RETURN_SUCCESS, -verbose => $SHOW_FULL_MANUAL )
    if $is_help_requested;

# check required options
pod2usage(
    -exitval => $RETURN_BAD_OPTIONS,
    -message => 'required parameter "conf" not defined',
    -verbose => $SHOW_USAGE_ONLY,
) unless $path_to_conf_file;

#-- init settings --------------------------------------------------------------
my $conf = Configurator->new( conf => $path_to_conf_file )->get_settings;

#-- init log -------------------------------------------------------------------
container->register( 'log', sub {
    return Log::Console->new( log_level => 'all' );
} );

#-- signal handlers ------------------------------------------------------------
require( catfile( $RealBin, 'signal_handlers.pl' ) );

#-- rpc client -----------------------------------------------------------------
my $rpc_client = JSON::RPC::Client->new();

$remote_server_url ||= $REMOTE_SERVER_URL;

$remote_server_url .= q{:}. $conf->local_port;

#-- echo test ------------------------------------------------------------------
{
    my $call_object = {
        method  => 'echo',
        params  => [ q{'echo' method} ],
    };

    my $response = $rpc_client->call( $remote_server_url, $call_object );

    if ( $response ) {
        if ( $response->is_error ) {
            container('log')->Error( 'error: '. $response->error_message );
        }
        else {
            if (
                $response->result
                    and @{ $response->result }[0] eq q{'echo' method}
            ) {
                container('log')->Note(
                    q{метод 'echo' вернул корректный результат: }
                    . @{ $response->result }[0]
                );
            }
            else {
                container('log')->Error(
                    q{метод 'echo' вернул некорректный результат}
                );
            }
        }
    }
    else {
        container('log')->Error( $rpc_client->status_line );
    }
}

#-- end ------------------------------------------------------------------------

__END__

=head1 NAME

storage_test.pl - утилита для тестирования удаленного JSON-RPC сервера.

=head1 SYNOPSIS

storage_test.pl [options]

 Options:
   --help            show full help message
   --conf            path to config file
   --url             remote server URL

=head1 USAGE

получение справочной информации:
/path/to/storage_test.pl --help

тестировать localhost-сервер:
/path/to/storage_test.pl --conf=./path_to_server_config

тестировать сервер расположеный на сайте google.com:
/path/to/storage_test.pl --conf=./path_to_server_config --url=http://google.com

=head1 DESCRIPTION

отправляет запрос к RPC-серверу и анализирует ответ. по дефолту сервер находится
по адресу localhost и эту предустановку можно переопределить параметром
командной строки. порт прослушиваемый сервером задан в конфиге

=head1 DEPENDENCIES

lib::abs (from CPAN)

Const::Fast (from CPAN)

JSON::RPC::Client (from CPAN)

JIP::ToolSet (from base_lib)

Configurator (from base_lib)

Log::Console (from base_lib)


=head1 EXIT STATUS

0 - программа выполнена успешно

1 - критическая ошибка программы

2 - неверные параметры командной строки

=head1 AUTHOR

Vladimir Zhavoronkov, <dolbanavt (at) Google Mail>

http://dolbanavt.livejournal.com/

=head1 LICENSE AND COPYRIGHT

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

=cut
